//
// Created by Lenovo on 2025/11/23.
//
#include "CrossGraph.h"

#include <cstdlib>

#include "../ListGraph/ListGraph.h"

CrossGraph * createCrossGraph(int n) {
    CrossGraph* crossGraph = (CrossGraph*)malloc(sizeof(CrossGraph));
    if (!crossGraph) {
        return NULL;
    }
    crossGraph->nodeCount = n;
    crossGraph->edgeCount = 0;
    crossGraph->nodes =(CrossGraphNode*)malloc(sizeof(int) * n);
    return crossGraph;
}

void releaseCrossGraph(CrossGraph *crossGraph) {
    int num = 0;
    if (crossGraph) {
        if (crossGraph->nodes) {
            for (int i = 0; i < crossGraph->nodeCount; i++) {
                CrossGraphEdge* edge = crossGraph->nodes[i].firstOut;
                CrossGraphEdge* tmp = nullptr;
                while (edge) {
                    tmp = edge;
                    edge = tmp->headNext;
                    free(tmp);
                    num++;
                }
            }
            free(crossGraph->nodes);
        }
    }
    free(crossGraph);
}

void initCrossGraph(CrossGraph *crossGraph, const char *names[], int num) {
    for (int i = 0; i < num; ++i) {
        crossGraph->nodes[i].no = i;
        crossGraph->nodes[i].show = names[i];
        crossGraph->nodes[i].firstIn = crossGraph->nodes[i].firstOut = NULL;
    }
}

void addCrossGraphEdge(CrossGraph *crossGraph, int tail, int head, int w) {
    CrossGraphEdge* edge = (CrossGraphEdge*)malloc(sizeof(CrossGraphEdge));
    if (!edge) {
        return;
    }
    edge->weight = w;

    edge->tail = tail;
    edge->tailNext = crossGraph->nodes[tail].firstOut;
    crossGraph->nodes[tail].firstOut = edge;

    edge->head = head;
    edge->headNext = crossGraph->nodes[head].firstOut;
    crossGraph->nodes[head].firstOut = edge;
}

int inDegreeCount(CrossGraph *crossGraph, int no) {
    int count = 0;
    CrossGraphEdge* edge = crossGraph->nodes[no].firstIn;
    while (edge != NULL) {
        count++;
        edge = edge->headNext;
    }
    return count;
}

int outDegreeCount(CrossGraph *crossGraph, int no) {
    int count = 0;
    CrossGraphEdge* edge = crossGraph->nodes[no].firstOut;
    while (edge != NULL) {
        count++;
        edge = edge->tailNext;
    }
    return count;
}
